


import 'dart:io';
import 'dart:isolate';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:ip_check_demo/showBasicAlertDialog.dart';
import 'package:ip_check_demo/utils/GetInputTextFieldUtils.dart';
import 'package:ip_check_demo/utils/hint_uitl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

class PingPage extends StatefulWidget{

  const PingPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return PingState();
  }
}


class PingState extends State<PingPage>{
  String Ip = '';
  TextEditingController _IpinpuController = TextEditingController();
  String text= '';

  List<Widget> listTiles = [];

  @override
  void initState() {

    getHistoryList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:
       AppBar(
         title: Text("Ping"),
       ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
            getStartIpInput()!,
            ElevatedButton(
              child: Text("Ping一下"),
              onPressed: () {
                PingFunc();
              },
            ),

          Container(
            padding: EdgeInsets.all(8),
            child:
            Text(text,
            style: const TextStyle(
              backgroundColor: Colors.black54,
              color: Colors.white
            ),),
          ),
          Container(
            padding: EdgeInsets.all(8),
            child:
            Text('历史记录',style: TextStyle(
              color: Colors.blue,
              fontSize: 20,
            ),),
          ),
          Expanded(child: Container(
            child:
            ListView.builder(
              itemBuilder: (c,i)=> Center(child: listTiles [i],) ,
              itemExtent: 100.0,
              itemCount: listTiles.length,
            ),
          )),

        ],
      ),
    );
  }

  PingFunc() async {

    if(Ip == '' || Ip == null){
      HintUtil.toast('ip为空');
      return null;
    }
      showBasicAlertDialog(context);

      print(Ip);
      text =  "";

      if(mounted){
        setState(() {
        });
      }


     ReceivePort port = ReceivePort();
     Isolate iso = await Isolate.spawn(checkConn,[port.sendPort,Ip]);
     String result = await port.first as String;
     text =  result.toString();

     closeBasicDialog(context);
     setHistoryIp(Ip);

     port.close();
     iso.kill();

     if(mounted){
       setState(() {
       });
     }
  }



  static Future<void> checkConn(List<dynamic> args) async {
    SendPort resultPort = args[0];
    bool isConnect = false;

    final ip = args[1];
    print(ip);
    final ProcessResult  response  ;
    try {
      final result = await InternetAddress.lookup(ip);
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {

        // final response = await Process.run('ping', ['-c', '1', '-W', '5', ip]);

        if (Platform.isWindows) {
          response = await Process.run('ping', ['/n', '4', '/w', '5000', ip]);
        } else {
          response =  await Process.run('ping', ['-c', '4', '-W', '5', ip]);
        }

        if (response.exitCode == 0) {
          isConnect =  true;

          print('isConnect $isConnect');
        }

        Isolate.exit(resultPort,response.stdout);
      }
      print('result 出错$result');
      isConnect =  false;
      // Isolate.exit(resultPort,response);
    } catch (e) {
      print('异常');
      isConnect =  false;
      // Isolate.exit(resultPort,response);
    }
  }

  getHistoryList() async {
    final SharedPreferences preferences = await SharedPreferences.getInstance();

    List<String>? ipsLists  =  await preferences.getStringList('ips');

    List<Widget> mIpList = [];
    if(ipsLists!= null){

      print('获取$mIpList');
      for(int i = 0; i < ipsLists.length;i ++){
        ListTile listTile = ListTile(

          leading: Icon(Icons.history),
          title: Text(
              ipsLists[i]
          ),
          onTap: (){
            print('点击onTap');
            _IpinpuController.text = ipsLists[i];
            Ip = _IpinpuController.text;
          },
        );
        mIpList.add(listTile);
      }
    }
    if(mounted){
      setState(() {
        listTiles = mIpList;
      });
    }

  }


  setHistoryIp(String ip) async{
    if(ip == null || ip == ''){
      return null;
    }

    final SharedPreferences preferences = await SharedPreferences.getInstance();

    List<String>? ipsLists  =  await preferences.getStringList('ips');

    if(ipsLists != null){

      if(!ipsLists.contains(ip)){
        ipsLists.add(ip);
        print('已有，开存$ip');
      }

    }else {
      ipsLists = [];
      ipsLists.add(ip);

      print('没有，建立一个开存$ip');
    }
    await preferences.setStringList('ips',ipsLists);


  }

  Widget? getStartIpInput(){
    return GetInputTextFieldUtils.getInputTextField(
      TextInputType.number,
      obscureText:false,
      controller: _IpinpuController,
      decoration: InputDecoration(
        hintText: "请输入ip",
        labelText: "ip",
        icon: const Icon(
          Icons.computer,
          size: 20.0,
        ),
        border: const OutlineInputBorder(),
        //使用 GestureDetector 实现手势识别
        suffixIcon: GestureDetector(
          child: Offstage(
            child: Icon(Icons.clear),
            offstage: Ip == '',
          ),
          //点击清除文本框内容
          onTap: () {
            this.setState(() {
              Ip = '';
              _IpinpuController.clear();
            });
          },
        ),
      ),
      onChanged: (value) {
        this.setState(() {
          Ip = value;
        });
      },
    );
  }

}